
#include "leak.h"

#ifdef __DEBUG__


//#include <cstdio>
//#include <cstring>

TrackInfo* p_first = nullptr;
TrackInfo* p_last = nullptr;

std::mutex _lock;

static void DeleteTrack(void* ptr){

	std::lock_guard<std::mutex> lock(_lock);

	TrackInfo* p_track = p_first;
	while(p_track)
	{
		if(p_track->ptr == ptr)
		{
			if(p_track->p_prev)
			{
				p_track->p_prev->p_next = p_track->p_next;
			}else
			{
				p_first = p_track->p_next;
			}
			if(p_track->p_next)
			{
				p_track->p_next->p_prev = p_track->p_prev;
			}else
			{
				p_last = p_track->p_prev;
			}
			free(p_track);
			return;
		} else
		{
			p_track = p_track->p_next;
		}
	}

}

void PrintUnfreed(){
	TrackInfo* p_track = p_first;
	printf("\n--------------Unfreed--------------\n");
	while(p_track)
	{
		printf("file: %s, line: %i\n", p_track->file_, p_track->line_);
		//std::cout << "file: " << p_track->file_ << ":" << p_track->line_ << std::endl;
		//std::cout << p_track << std::endl;
		TrackInfo* p_next_track = p_track->p_next;
		free(p_track);
		p_track = p_next_track;
	}
	printf("-----------------------------------\n");
	p_first = nullptr;
	p_last = nullptr;
}
/*
void operator delete(void* ptr){
	DeleteTrack(ptr);
	free(ptr);
}
*/
void operator delete(void* ptr) noexcept (true){
	DeleteTrack(ptr);
	free(ptr);
}
/*
void operator delete[](void* ptr){
	DeleteTrack(ptr);
	free(ptr);
}
*/
void operator delete[](void* ptr) noexcept (true){
	DeleteTrack(ptr);
	free(ptr);
}

#endif


